﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace tiDE.Support
{
    /// <summary>
    /// Exposes all settings and manages the storage
    /// of them.
    /// </summary>
    [Serializable]
    public class SettingsProvider
    {
        private static string settingsPath;
        private static SettingsProvider Instance;

        internal static void Initialize()
        {
            Instance = new SettingsProvider();

            settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tidenv", "settings.dat");

            if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tidenv")))
                Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tidenv"));

            if (!File.Exists(settingsPath))
            {
                Instance.StartPageFeedProviders = new List<string>();
                Instance.StartPageFeedProviders.Add("http://cemetech.net/forum/rss.php");
                Instance.StartPageFeedProviders.Add("http://www.omnimaga.org/index.php?action=.xml;type=rss");
                Instance.StartPageFeedProviders.Add("http://www.ticalc.org/rss/news.rss");
                Save();
            }
            else
            {
                Load();
            }
        }

        /// <summary>
        /// Saves settings to the disk
        /// </summary>
        public static void Save()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SettingsProvider));
            Stream s = File.Open(settingsPath, FileMode.OpenOrCreate);
            serializer.Serialize(s, GetInstance());
            s.Close();
        }

        /// <summary>
        /// Loads settings from the disk (useful for cancelling)
        /// </summary>
        public static void Load()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SettingsProvider));
            Stream s = File.Open(settingsPath, FileMode.Open);
            Instance = (SettingsProvider)serializer.Deserialize(s);
            s.Close();
        }

        public static SettingsProvider GetInstance()
        {
            return Instance;
        }

        public List<string> StartPageFeedProviders;
    }
}
